import requests
import re

def getHTML(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
                      ' Chrome/68.0.3423.2 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=30,headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
       return ""

def parsePage(ilt,html):
    try:
        PLT = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
        TLT = re.findall(r'\"raw_title\"\:\".*?\"',html)
        for i in range(len(PLT)):
            price = eval(PLT[i].split(':')[1]) # qu ""
            title = eval(TLT[i].split(':')[1])
            ilt.append([price,title])
    except:
        print(0)

def printList(ilt):
    tplt = "{:4}\t{:8}\t{:16}"
    print(tplt.format("序号","价格","名称"))
    count = 0
    for g in ilt:
        count+=1
        print(tplt.format(count,g[0],g[1]))

if __name__ == '__main__':
    goods = '手机'
    depth = 3
    start_url = 'https://s.taobao.com/search?q='+goods
    infoList = []
    for i in  range(depth):
        try:
            url = start_url+'&='+ str(44*i)
            html = getHTML(url)
            parsePage(infoList,html)
        except:
                continue
    printList(infoList)

